<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/16
 * Time: 10:39
 */

namespace app\common\model;


use think\Model;

class Member extends Model
{
    /**
     * 用户登陆模型类
     * @param $username
     * @param $password
     */
    public function login($username,$password)
    {
        $user = $this->info($username,false);
        if($user){
            $user->toArray();
            if(password_verify($password, $user['password'])){
                $this->updateLogin($user['id']); //更新用户登录信息
                $this->autoLogin($user); //进行用户登录操作
                return $user['id']; //登录成功，返回用户ID
            }
        }
    }

    /**
     * 用户登录
     * @param $username 用户名
     * @param bool $passname 是否返回密码 默认不返回 true 不返回，false 返回
     * @param int $type （1-用户名，2-邮箱，3-手机，4-UID）
     * @return int
     */
    public function info($username,$password = true,$type = 1)
    {
        $map = array();
        switch ($type) {
            case 1:
                $map['username'] = $username;
                break;
            case 2:
                $map['email'] = $username;
                break;
            case 3:
                $map['mobile'] = $username;
                break;
            case 4:
                $map['id'] = $username;
                break;
            default:
                return 0; //参数错误
        }

        if($password==true){
            $res = Member::where($map)->field('password',$password)->find();
        } else {
            $res = Member::where($map)->find();
        }

        return $res;
    }

    /**
     * 更新用户登录信息
     * @param  integer $uid 用户ID
     */
    protected function updateLogin($uid){
        $data = array(
            'id'              => $uid,
            'last_login_time' => time(),
            'last_login_ip'   => get_client_ip(1),
        );
        $this->update($data);
    }

    /**
     * 自动登录用户
     * @param  integer $user 用户信息数组
     */
    private function autoLogin($user){

        /* 记录登录SESSION和COOKIES */
        $auth = array(
            'uid'             => $user['id'],
            'username'        => $user['username'],
            'last_login_time' => $user['last_login_time'],
        );
        session('user_auth', $auth);
        session('user_auth_sign', data_auth_sign($auth));
    }

    /**
     * 注销当前用户
     * @return void
     */
    public function logout(){
        session('user_auth', null);
        session('user_auth_sign', null);
    }
}